package com.liuzhilong.infrastructure.basic.proxy.dynamic.jdk;

import lombok.AccessLevel;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 简单的代理。
 * @author longandai@163.com
 */
@Setter(AccessLevel.PRIVATE)
@Accessors(chain = true)
public class SimpleJDKProxy<T> implements InvocationHandler {
    private T target;




    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(getClass().getName()+" pre");
        if("do2".equalsIgnoreCase(method.getName())){
            return getClass().getName()+" 特殊拦截了do2,返回了内容。";
        }
        try {
            Object result = method.invoke(target,args);
            System.out.println(getClass().getName()+" post");
            return result;
        }catch (Throwable throwable){
            System.out.println(getClass().getName()+" exception");
            throwable.printStackTrace();
            throw throwable;
        }
    }
    public <T> T getProxy() {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    public static <T> T  createProxy(T target){
        return new SimpleJDKProxy<T>().setTarget(target).getProxy();
    }
}
